<template>
  <a-row>
    <a-col :span="24">
      <a-card>
        <!-- 商品基本信息 -->
        <div class="goods-info">
          <div class="info-title">商品基本信息</div>
          <a-form
            ref="formRef"
            :model="form"
            :rules="rules"
            :label-col="{ span: 5 }"
            :wrapper-col="{ span: 12 }"
          >
            <a-form-item ref="goodsName" label="商品名称" name="goodsName">
              <a-input
                placeholder="商品名称"
                style="width: 220px"
                v-model:value="form.goodsName"
              />
            </a-form-item>

            <a-form-item label="商品分类" ref="categoryId" name="categoryId">
              <a-select
                v-model:value="form.categoryId"
                placeholder="商品分类"
                style="width: 220px"
                :allowClear="true"
                show-search
                :filter-option="filterOptionPartent"
              >
                <a-select-option v-for="c in classList" :key="c._id" :value="c._id">
                  {{ c.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="商品品牌" ref="brandId" name="brandId">
              <a-select
                v-model:value="form.brandId"
                placeholder="商品品牌"
                style="width: 220px"
                :allowClear="true"
                show-search
                :filter-option="filterOptionPartent"
              >
                <a-select-option v-for="c in brandList" :key="c._id" :value="c._id">
                  {{ c.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="商品货号" ref="goodsNo" name="goodsNo">
              <a-input
                placeholder="商品货号"
                style="width: 220px"
                v-model:value="form.goodsNo"
              />
            </a-form-item>
          </a-form>
        </div>
        <!-- 商品规格 -->
        <div class="mix-containter">
          <div class="mix-title">商品规格</div>
          <div class="mix-item">
            <div class="item-bar" v-for="(mixMax, index) in mixMaxItem" :key="mixMax.key">
              <div class="bar-nav">
                <div class="nav-lf">
                  <p>规格项:</p>
                  <a-input
                    v-model:value="mixMax.spaceName"
                    :allowClear="true"
                    size="small"
                  />
                </div>
                <div class="nav-lr">
                  <a @click="onRemoveMixItem(index)">删除</a>
                </div>
              </div>
              <div class="bar-value">
                <div class="value-box">
                  <div
                    class="value"
                    v-for="(mixMin, i) in mixMax.mixList"
                    :key="mixMin.key"
                  >
                    <a-input
                      @blur="onBlurMixValue(mixMin)"
                      v-model:value.trim="mixMin.mixName"
                      :style="{ width: '120px', marginRight: '10px' }"
                      v-if="mixMin.isShowInp"
                    />
                    <span class="txt" v-else @click="onCheckoutValue(mixMin)"
                      >{{ mixMin.mixName }}
                      <span class="ico" @click="onRemoveMinValue(mixMax.mixList, i)">
                        <CloseCircleOutlined />
                      </span>
                    </span>
                  </div>
                </div>
                <div class="add-value">
                  <a @click="onAddMaxValue(index)"> 添加规格值+</a>
                </div>
              </div>
            </div>
            <div class="add-btn">
              <a-button type="primary" @click="onAddMixItem">添加规格项+</a-button>
            </div>
          </div>
        </div>
        <!-- 规格表格 -->
        <div class="mix-table">
          <a-table bordered :columns="columns" rowKey="key" size="small"  :pagination="false" :data-source="data">
            <template #price="{ record }">
              <a-input-number v-model:value="record.price" />
            </template>
            <template #size="{ record }">
              <div class="size">
               <a-input-number placeholder="长" v-model:value="record.mixLength" />*
                <a-input-number placeholder="宽" v-model:value="record.mixWidth" />*
                <a-input-number placeholder="高" v-model:value="record.mixHeight" />
              </div>
            </template>
            <template #designSketch="{ record }">
              <div class="design-img">
                <a-upload
                  :multiple="true"
                  list-type="picture-card"
                  name="file"
                  v-model:file-list="record.designSketch"
                  :before-upload="(e, fileList) => onBeforeUpload(e, fileList, record)"
                  :customRequest="(e) => onCustomRequest(e, record)"
                >
                  <div v-if="record.designSketch.length < 8">
                    <plus-outlined />
                    <div class="ant-upload-text">上传</div>
                  </div>
                </a-upload>
              </div>
            </template>
          </a-table>
        </div>
      </a-card>
    </a-col>
  </a-row>
</template>

<script>
import { reactive, ref, toRefs, watch } from "vue";
import { message } from "ant-design-vue";
import { watchMix } from "./mixDataWatch"; //处理数据变化方法
const rules = {
  goodsName: [
    { required: true, message: "请输入", trigger: ["change", "blur"], type: "string" },
    {
      message: "商品名称长度由0-18位组成",
      min: 0,
      max: 18,
      trigger: ["change", "blur"],
      type: "string",
    },
  ],
  categoryId: [
    { required: true, message: "请选择", trigger: ["change", "blur"], type: "number" },
  ],
  brandId: [
    { required: true, message: "请选择", trigger: ["change", "blur"], type: "number" },
  ],
  goodsNo: [
    { required: true, message: "请输入", trigger: ["change", "blur"], type: "string" },
  ],
};
const column = [
  {
    title: "商品规格",
    dataIndex: "name",
    key: "name",
    align: "center",
    children: [
      {
        title: "",
        dataIndex: "mixName1",
        align: "center",
        width: 200,
      },
    ],
  },
  {
    title: "商品价格",
    dataIndex: "price",
    width: 100,
    align: "center",
    slots: {
      customRender: "price",
    },
  },

  {
    title: "尺寸(长*宽*高)(mm)",
    dataIndex: "size",
    width: 160,
    slots: {
      customRender: "size",
    },
    align: "center",
  },
  {
    title: "商品效果图",
    dataIndex: "designSketch",
    align: "center",
    slots: {
      customRender: "designSketch",
    },
  },
];
import { imgBatchUpload } from "@/api/commodityCenter";
export default {
  setup() {
    const form = reactive({
      goodsName: null,
      categoryId: null,
      sort: null,
      brandId: null,
      _id: null,
      goodsNo: null,
    });
    const parametr = reactive({
      classList: [],
      brandList: [],
      beforeImgFile: [],
      afterImgFile: [],
    });
    const data = ref([]);
    const columns = ref(column);
    const mixMaxItem = ref([
      {
        spaceName: "",
        key: -1,
        mixList: [],
      },
    ]);
    //监听规格项数据变化
    watch(mixMaxItem.value, (newValue, oldValue) => {
      const attrColumns = columns.value[0].children;
      const result = watchMix(newValue, oldValue, attrColumns, data.value);
      columns.value[0].children = result.column;
      data.value = result.data;
    });
    // 添加大项
    const onAddMixItem = () => {
      const minMax = {
        spaceName: "",
        key: Math.random() * 1000,
        mixList: [],
      };
      if (mixMaxItem.value.length >= 4) {
        return message.warning("最多添加4项");
      }
      mixMaxItem.value.push(minMax);
    };
    //删除大项
    const onRemoveMixItem = (index) => {
      mixMaxItem.value.splice(index, 1);
    };
    //添加小项
    const onAddMaxValue = (index) => {
      const minMin = {
        mixName: "",
        key: Math.random() * 1000,
        isShowInp: true,
      };
      mixMaxItem.value[index].mixList.push(minMin);
    };
    //点击切换input输入
    const onCheckoutValue = (mixMin) => {
      mixMin.isShowInp = true;
    };
    //失焦隐藏 input
    const onBlurMixValue = (mixMin) => {
      mixMin.isShowInp = false;
    };
    //删除规格值
    const onRemoveMinValue = (minList, i) => {
      minList.splice(i, 1);
    };

    //上传图片前检测
    const onBeforeUpload = (file, fileList, record) => {
      return new Promise(async (reslove, reject) => {
        const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
        const isLt2M = file.size / 1024 / 1024 < 2;
        parametr.beforeImgFile.push(file);
        if (!isJpgOrPng || !isLt2M) {
        } else {
          parametr.afterImgFile.push(file);
        }
        // 判断批量上传图格式是否符合要求
        //符合要求的数量 和已上传的数量不能超过 8
        if (
          parametr.afterImgFile.length > 8 ||
          parametr.afterImgFile.length + record.designSketch.length > 8
        ) {
          parametr.beforeImgFile = [];
          parametr.afterImgFile = [];
          return message.error("效果图最多上传八张");
        }

        if (parametr.beforeImgFile.length == fileList.length) {
          if (parametr.afterImgFile.length == fileList.length) {
            return reslove();
          }
          parametr.beforeImgFile = [];
          parametr.afterImgFile = [];
          return message.error("图片格式jpg/png!，图片大小限制2MB!");
        }
      });
    };
    //图片上传
    const onCustomRequest = (file, record) => {
      const formData = new FormData();
      parametr.afterImgFile.forEach((v) => {
        formData.append("file", v);
      });

      imgBatchUpload(formData).then((res) => {
        const imgArr = res.data;
        const addImg = imgArr.map((v) => {
          let file = {
            uid: v.path,
            name: v.path,
            status: "done",
            url: v.path,
          };
          return file;
        });

        record.designSketch = record.designSketch
          .concat(addImg)
          .filter((v) => v.status == "done");
        parametr.beforeImgFile = [];
        parametr.afterImgFile = [];
      });
    };

    const filterOptionPartent = (input, option) => {
      return option.children[0].children.toLowerCase().indexOf(input.toLowerCase()) >= 0;
    };
    return {
      data,
      columns,
      rules,
      form,
      mixMaxItem,
      onAddMixItem,
      onRemoveMixItem,
      onAddMaxValue,
      onCheckoutValue,
      onBlurMixValue,
      onRemoveMinValue,
      ...toRefs(parametr),
      onCustomRequest,
      onBeforeUpload,
      filterOptionPartent,
    };
  },
};
</script>

<style scoped lang="less">
.goods-info {
  .info-title {
    font-weight: bold;
    font-size: 16px;
    margin: 10px 0px;
  }
}
.mix-containter {
  .mix-title {
    font-weight: bold;
    font-size: 16px;
    margin: 10px 0px;
  }
  .mix-item {
    padding: 0px 15px;
    .item-bar {
      .bar-nav {
        display: flex;
        align-items: center;
        justify-content: space-between;
        height: 50px;
        background-color: #f5f7fa;
        padding: 0px 15px;
        .nav-lf {
          display: flex;
          align-items: center;
          p {
            min-width: 80px;
            margin: 0 !important;
          }
        }
      }
      .bar-value {
        padding: 20px 80px;
        .value-box {
          display: flex;
          flex-wrap: wrap;
          margin-bottom: 10px;
        }
        .value {
          margin-right: 10px;
          margin-bottom: 8px;

          .txt {
            position: relative;
            padding: 0px 20px;
            border-color: #eceef1;
            display: inline-block;
            border-width: 1px;
            border-style: solid;
            line-height: 30px;
            -webkit-box-shadow: none;
            box-shadow: none;
            color: #5e6166;
            -webkit-box-sizing: border-box;
            box-sizing: border-box;
            height: 30px;
            font-size: 12px;
            left: 0px;
            text-align: center;
            cursor: pointer;
            .ico {
              position: absolute;
              top: -15px;
              right: -6px;
              cursor: pointer;
              display: none;
            }
            &:hover .ico {
              display: block;
            }
          }
        }
      }
    }
  }
}
.mix-table {
  margin-top: 20px;
  .size {
    display: flex;
    align-items: center;
    color: red;
  }
  /deep/ .ant-input-number-handler-wrap {
    display: none;
  }
  /deep/ .ant-upload-list-picture-card .ant-upload-list-item-info::before {
    left: 0;
  }
}
</style>
